// miniprogram/pages/search/index.js
const request = require('../../api/request');

Page({
  data: {
    keyword: '',
    resultList: [],
    loading: false,
    searchType: 'member' // 搜索类型: member-普通搜索, tree-树搜索
  },
  onInput(e) {
    this.setData({ keyword: e.detail.value });
  },
  
  // 清除搜索内容
  clearSearch() {
    this.setData({ 
      keyword: '',
      resultList: []
    });
  },
  
  onSearch() {
    const keyword = this.data.keyword.trim();
    if (!keyword) {
      wx.showToast({ title: '请输入关键词', icon: 'none' });
      return;
    }

    this.setData({ loading: true, resultList: [] });

    if (this.data.searchType === 'tree') {
      // 使用家族树搜索API
      this.searchFamilyTree(keyword);
    } else {
      // 使用普通成员搜索API
      this.searchMembers(keyword);
    }
  },
  
  searchMembers(keyword) {
    // 只传q参数，后端支持姓名或地名任意模糊查找
    request.get('/members', { q: keyword, page: 1, size: 20 }).then(res => {
      const resultList = (res && res.records) ? res.records : [];
      this.setData({ resultList, loading: false });
    }).catch(() => {
      this.setData({ loading: false });
      wx.showToast({ title: '搜索失败', icon: 'none' });
    });
  },
  
  searchFamilyTree(keyword) {
    // 获取登录信息，确定clanId
    const userInfo = wx.getStorageSync('userInfo') || {};
    const clanId = userInfo.clanId;
    
    // 调用家族树搜索API
    request.get('/family/tree/search', { 
      q: keyword,
      clanId: clanId,
      limit: 20
    }).then(res => {
      const resultList = res || [];
      this.setData({ resultList, loading: false });
    }).catch(() => {
      this.setData({ loading: false });
      wx.showToast({ title: '搜索失败', icon: 'none' });
    });
  },
  
  switchSearchType() {
    const newType = this.data.searchType === 'member' ? 'tree' : 'member';
    this.setData({ 
      searchType: newType,
      resultList: [] // 清空结果
    });
  },

  // 跳转到成员详情页
  goToMemberDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/memberdetail/index?id=${id}` });
  },
  
  // 跳转到家族树并高亮该成员
  goToTreeWithMember(e) {
    const id = e.currentTarget.dataset.id;
    const name = e.currentTarget.dataset.name;
    // 将成员ID和名称保存到全局状态或本地缓存
    wx.setStorageSync('highlightMember', {
      id: id,
      name: name
    });
    
    // 跳转到家族树页面
    wx.switchTab({
      url: '/pages/tree/index'
    });
  }
});